package bb.lanxing.activity.routebook;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import com.umeng.socialize.net.dplus.CommonNetImpl;
import com.umeng.socialize.net.utils.SocializeProtocolConstants;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.common.config.Constants;
import bb.lanxing.util.thread.BaseTaskWithCallBack;
import bb.lanxing.util.thread.ImageUploadTask;
import bb.lanxing.util.thread.ThreadPools;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.FileProvider7;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.ImageUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.image.GlideUtils;
import bb.lanxing.util.img.ImageChooserUtil;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.PopupMenu;

public class RouteBookWaypointEditActivity extends BaseActivity {
    final private static String TAG = "LushuWaypointEditActivity";
    private static final int IMAGE_FROM_PHOTO = 0;
    private static final int IMAGE_FROM_FILE = 1;
    private String content;
    private String dir;
    private int i;
    private File imageFile;
    private String imagePath;
    private String lastPath;
    private ImageButton photoAddBtn;
    private LinearLayout photoContent;
    private LinearLayout photoView;
    private int position;
    private Switch showWaypointSwitch;
    private String title;
    private TextView waypointDescView;
    private TextView waypointTitleView;
    private ArrayList<String> urlList = new ArrayList<>();
    private ArrayList<Object> oldList = new ArrayList<>();
    private boolean isCommit = false;
    private int clickCount = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lushu_waypoint_edit);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        initView();
    }

    private void initView() {
        int i = -1;
        this.position = getIntent().getIntExtra(CommonNetImpl.POSITION, -1);
        this.title = getIntent().getStringExtra("title");
        this.content = getIntent().getStringExtra("content");
        String stringExtra = getIntent().getStringExtra(SocializeProtocolConstants.IMAGE);
        boolean booleanExtra = getIntent().getBooleanExtra("isShow", true);
        String str = this.title;
        if (str != null) {
            this.waypointTitleView.setText(str);
        }
        String str2 = this.content;
        if (str2 != null) {
            this.waypointDescView.setText(str2);
        }
        this.showWaypointSwitch.setChecked(booleanExtra);
        this.showWaypointSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> RouteBookWaypointEditActivity.this.showWaypointSwitch.setChecked(isChecked));
        if (TextUtils.isEmpty(stringExtra)) {
            return;
        }
        Log.d(TAG, "old image :" + stringExtra);
        ArrayList<Object> arrayList = new ArrayList<>(Arrays.asList(stringExtra.split(";")));
        this.oldList = arrayList;
        for (Object obj : arrayList) {
            i++;
            addImageButton(obj.toString(), i);
        }
    }

    private void addImage() {
        uploadImage();
    }

    private void uploadImage() {
        if (!AppFileUtils.isSdCardAvailable()) {
            App.getContext().showMessage(R.string.sdcard_null);
            return;
        }
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_CACHE);
        this.dir = buildExternalDirectoryPath;
        if (buildExternalDirectoryPath == null) {
            return;
        }
        new BiciAlertDialogBuilder(this).setTitle(R.string.dialog_choose_image).setItems(new CharSequence[]{getText(R.string.dialog_take_photo), getText(R.string.dialog_photo_album)}, (dialog, which) -> {
            if (which == 0) {
                RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getCameraPermission()).permissionRequestEachCombined(RouteBookWaypointEditActivity.this, new RxPermissionUtil.PermissionCallBack() {
                    @Override
                    public void deny() {
                    }

                    @Override
                    public void granted() {
                        if (!App.isManagersInit) {
                            App.getContext().initManagersWithPermissions();
                        }
                        RouteBookWaypointEditActivity routeBookWaypointEditActivity = RouteBookWaypointEditActivity.this;
                        String str = RouteBookWaypointEditActivity.this.dir;
                        routeBookWaypointEditActivity.imageFile = new File(str, System.currentTimeMillis() + ".jpg");
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra("output", FileProvider7.getUriForFile(RouteBookWaypointEditActivity.this, RouteBookWaypointEditActivity.this.imageFile));
                        try {
                            RouteBookWaypointEditActivity.this.startActivityForResult(intent, 0);
                        } catch (Exception unused) {
                            App.getContext().showMessage(R.string.toast_find_no_image_app);
                        }
                    }
                });
            } else if (which == 1) {
                RouteBookWaypointEditActivity routeBookWaypointEditActivity = RouteBookWaypointEditActivity.this;
                ImageChooserUtil.startChooser(routeBookWaypointEditActivity, 3, routeBookWaypointEditActivity.urlList, 1);
            }
        }).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == 0) {
                photoImagePath(this.imageFile.getAbsolutePath());
            } else if (requestCode == 1) {
                fileImagePath(data);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void fileImagePath(Intent data) {
        for (String next : ImageChooserUtil.getSelectedImagePath(data)) {
            if (!this.urlList.contains(next)) {
                int imageDegree = CommonUtil.getImageDegree(next);
                Bitmap canUploadSourceImage = ImageUtil.getCanUploadSourceImage(next);
                if (imageDegree != 0) {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(imageDegree);
                    canUploadSourceImage = Bitmap.createBitmap(canUploadSourceImage, 0, 0, canUploadSourceImage.getWidth(), canUploadSourceImage.getHeight(), matrix, true);
                }
                String str = this.dir + System.currentTimeMillis() + ".jpg";
                ImageUtil.storeJPGImage(canUploadSourceImage, str, 80);
                addImageButton(str);
            }
        }
    }

    public void photoImagePath(String picPath) {
        int imageDegree = CommonUtil.getImageDegree(picPath);
        Bitmap canUploadSourceImage = ImageUtil.getCanUploadSourceImage(picPath);
        if (imageDegree != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(imageDegree);
            canUploadSourceImage = Bitmap.createBitmap(canUploadSourceImage, 0, 0, canUploadSourceImage.getWidth(), canUploadSourceImage.getHeight(), matrix, true);
        }
        String str = this.dir + System.currentTimeMillis() + ".jpg";
        ImageUtil.storeJPGImage(canUploadSourceImage, str, 80);
        addImageButton(str);
    }

    public void addImageButton(String path) {
        int size = this.urlList.size();
        ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.lushu_commit_add_photo_item, this.photoContent, false);
        this.photoContent.addView(imageView);
        imageView.setTag(size);
        GlideUtils.Companion companion = GlideUtils.companion;
        companion.loadImage(this, "file://" + path, imageView, R.drawable.ic_img_avatar_team, R.drawable.ic_img_avatar_team);
        this.urlList.add(size, path);
        if (this.oldList.size() + this.urlList.size() == 3) {
            this.photoAddBtn.setVisibility(View.GONE);
        }
        imageView.setOnClickListener(view -> RouteBookWaypointEditActivity.this.showDeleteOption((ImageView) view, (Integer) view.getTag(), 1));
    }

    public void addImageButton(String imagePath, final int i) {
        ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.lushu_commit_add_photo_item, this.photoContent, false);
        this.photoView.addView(imageView);
        imageView.setTag(i);
        GlideUtils.companion.loadImage(this, imagePath, imageView, R.drawable.ic_img_avatar_team, R.drawable.ic_img_avatar_team);
        if (this.oldList.size() == 3) {
            this.photoAddBtn.setVisibility(View.GONE);
        }
        imageView.setOnClickListener(view -> RouteBookWaypointEditActivity.this.showDeleteOption((ImageView) view, (Integer) view.getTag(), 0));
    }

    void showDeleteOption(final ImageView imageButton, final int tag, final int flag) {
        PopupMenu popupMenu = new PopupMenu(this, imageButton);
        popupMenu.inflate(R.menu.menu_image_delete);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(item -> {
            if (flag == 0) {
                RouteBookWaypointEditActivity.this.deleteOldpic(imageButton, tag);
                return true;
            }
            RouteBookWaypointEditActivity.this.deleteNewpic(imageButton, tag);
            return true;
        });
    }

    public void deleteNewpic(final ImageView imageButton, int tag) {
        imageButton.setVisibility(View.GONE);
        this.photoAddBtn.setVisibility(View.VISIBLE);
        this.photoContent.removeViewAt(tag);
        this.urlList.remove(tag);
        while (tag < this.photoContent.getChildCount()) {
            ImageView imageView = this.photoContent.getChildAt(tag).findViewById(R.id.photoLushu);
            imageView.setTag((Integer) imageView.getTag() - 1);
            tag++;
        }
        if (this.isCommit) {
            this.isCommit = false;
        }
        if (this.urlList.isEmpty()) {
            this.imagePath = "";
        }
    }

    public void deleteOldpic(final ImageView imageButton, int tag) {
        imageButton.setVisibility(View.GONE);
        this.photoAddBtn.setVisibility(View.VISIBLE);
        this.photoView.removeViewAt(tag);
        this.oldList.remove(0);
        while (tag < this.photoView.getChildCount()) {
            ImageView imageView = this.photoView.getChildAt(tag).findViewById(R.id.photoLushu);
            imageView.setTag((Integer) imageView.getTag() - 1);
            tag++;
        }
    }

    private void uploadImageToUPYun(String path, final int count) {
        Log.d(Constants.TAG, "uploadImageToUPYun local path === " + path);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("sourceFile", path);
        hashMap.put("saveKey", ImageUtil.buildLushuWaypointImagePath());
        ImageUploadTask<String> imageUploadTask = new ImageUploadTask<>(hashMap);
        imageUploadTask.setOnGetResultListener((BaseTaskWithCallBack.OnGetResultListener<String>) (flag, result) -> {
            if (flag) {
                RouteBookWaypointEditActivity.this.toast(R.string.toast_upload_image_successful);
                String str = Constants.UPYUN_HOST + result;
                if (TextUtils.isEmpty(RouteBookWaypointEditActivity.this.imagePath)) {
                    RouteBookWaypointEditActivity.this.imagePath = str;
                } else {
                    RouteBookWaypointEditActivity.this.imagePath = RouteBookWaypointEditActivity.this.imagePath + ";" + str;
                }
                RouteBookWaypointEditActivity.this.i++;
                if (RouteBookWaypointEditActivity.this.i == count) {
                    RouteBookWaypointEditActivity.this.runOnUiThread(() -> {
                        RouteBookWaypointEditActivity.this.i = 0;
                        AppFileUtils.cleanDirectory(RouteBookWaypointEditActivity.this.dir);
                        RouteBookWaypointEditActivity.this.isCommit = true;
                        RouteBookWaypointEditActivity.this.release();
                    });
                    return;
                }
                return;
            }
            RouteBookWaypointEditActivity.this.toast(R.string.toast_upload_image_failed);
            RouteBookWaypointEditActivity.this.runOnUiThread(() -> {
                RouteBookWaypointEditActivity.this.isCommit = false;
                RouteBookWaypointEditActivity.this.dismissLoadingDialog();
                RouteBookWaypointEditActivity.this.i = 0;
                RouteBookWaypointEditActivity.this.clickCount = 0;
            });
        });
        ThreadPools.getInstance().addTask(imageUploadTask);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_route_waypoint_edit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (R.id.action_done == item.getItemId()) {
            doCommit();
        }
        return super.onOptionsItemSelected(item);
    }

    private void doCommit() {
        int i = this.clickCount + 1;
        this.clickCount = i;
        if (i == 1) {
            if (!App.getContext().isUserSignin()) {
                App.getContext().userSignin();
                return;
            }
            showLoadingDialog(R.string.dialog_committing, false);
            if (!this.isCommit && !this.urlList.isEmpty()) {
                this.imagePath = "";
                for (String s : this.urlList) {
                    uploadImageToUPYun(s, this.urlList.size());
                    try {
                        Thread.sleep(200L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return;
            }
            release();
            return;
        }
        toast(R.string.dialog_committing);
    }

    public void release() {
        Iterator<String> it2 = null;
        dismissLoadingDialog();
        String trim = this.waypointTitleView.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            trim = this.title;
        }
        String trim2 = this.waypointDescView.getText().toString().trim();
        if (TextUtils.isEmpty(trim2)) {
            trim2 = this.content;
        }
        String str = "";
        if (!this.oldList.isEmpty()) {
            while (this.oldList.iterator().hasNext()) {
                str = str + it2.next() + ";";
            }
        }
        if (!TextUtils.isEmpty(str) && !TextUtils.isEmpty(this.imagePath)) {
            this.lastPath = str + this.imagePath;
        } else if (!TextUtils.isEmpty(str)) {
            this.lastPath = str;
        } else if (!TextUtils.isEmpty(this.imagePath)) {
            this.lastPath = this.imagePath;
        }
        Log.d(TAG, "last  imagePath:" + this.lastPath);
        Intent intent = new Intent();
        intent.putExtra(CommonNetImpl.POSITION, this.position);
        intent.putExtra("title", trim);
        intent.putExtra("content", trim2);
        intent.putExtra(SocializeProtocolConstants.IMAGE, this.lastPath);
        intent.putExtra("isShow", this.showWaypointSwitch.isChecked());
        setResult(Constants.RESULT_CODE_LUSHU_WAYPOINT_EDIT, intent);
        finish();
    }

    private void bindView(View bindSource) {
        this.showWaypointSwitch = bindSource.findViewById(R.id.showWaypointSwitch);
        this.waypointTitleView = bindSource.findViewById(R.id.waypointTitleView);
        this.waypointDescView = bindSource.findViewById(R.id.waypointDescView);
        this.photoAddBtn = bindSource.findViewById(R.id.photoAddBtn);
        this.photoContent = bindSource.findViewById(R.id.photoCotent);
        this.photoView = bindSource.findViewById(R.id.photoView);
        this.photoAddBtn.setOnClickListener(view -> addImage());
    }
}